package dj.action;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;

import dj.Constant;
import dj.action.base.BaseAction;
import dj.dwr.MessagePush;
import dj.model.Tuser;
import dj.model.UserExtend;
import dj.pageModel.Json;
import dj.pageModel.Pmenu;
import dj.pageModel.Puser;
import dj.pageModel.PuserExtend;
import dj.pageModel.TreeNode;
import dj.service.MenuService;
import dj.service.SysRoleService;
import dj.service.UserService;
import dj.utils.StringUtils;

@Action("userAction")
public class UserAction extends BaseAction implements ModelDriven<Puser> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UserAction.class);

	private UserService userService;

	private MenuService menuService;

	private MessagePush messagePush;

	private SysRoleService sysRoleService;

	private Puser user = new Puser();

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public MenuService getMenuService() {
		return menuService;
	}

	@Autowired
	public void setMenuService(MenuService menuService) {
		this.menuService = menuService;
	}

	public MessagePush getMessagePush() {
		return messagePush;
	}

	@Autowired
	public void setMessagePush(MessagePush messagePush) {
		this.messagePush = messagePush;
	}

	public SysRoleService getSysRoleService() {
		return sysRoleService;
	}

	@Autowired
	public void setSysRoleService(SysRoleService sysRoleService) {
		this.sysRoleService = sysRoleService;
	}

	public Puser getModel() {
		return user;
	}

	// public void doNotNeedSession_register() throws Exception {
	// Json json = new Json();
	// try {
	// if (null == user || null == user.getName() || null == user.getPwd()) {
	// json.setMsg("注册失败，用户名和密码不能为空！");
	// } else {
	// userService.save(user);
	// json.setSuccess(true);
	// json.setMsg("注册成功！");
	// }
	// } catch (Exception e) {
	// logger.error(e.getMessage());
	// e.printStackTrace();
	// json.setMsg("注册失败！" + e.getStackTrace());
	// }
	// super.writeToJson(json);
	// }

	public void doNotNeedSession_login() {
		Json json = new Json();
		try {
			Puser u = userService.login(user);
			if (null != u) {
				if (Constant.STATE_CLOSE == u.getUserState()) {
					json.setMsg("您的账号已被锁定，如有疑问，请与管理员联系！");
				} else {
					HttpSession usession = Constant.onlineUserSession.get(u.getId());
					Puser loginUser = null;
					if (null != usession) {
						try {
							loginUser = (Puser) usession.getAttribute(Constant.USER_SESSION);
						} catch (Exception e) {
						}
					}
					if (null != loginUser) {
						String hasLogin = "$.messager.confirm('提示', '该用户已登录，IP:" + loginUser.getIp() + "，是否要继续登录？', function(r){" + "if(r){ " + "$('#user-login-form').form('submit', { " + "url: '${pageContext.request.contextPath }/userAction!doNotNeedSession_mandateLogin.action', " + "onSubmit: function(){ " + "$.messager.progress({	text : '提交数据，请等待...'});	" + "},  " + "success: function(data){" + "var d = $.parseJSON(data);" + "if (d.success) {" + "location.reload(false);" + "} else{" + "$('#user-login').find('input[name=name]').focus(); " + "$.messager.show({msg : d.msg,title : '提示'}); " + "$.messager.progress('close');" + "}  " + "}" + "});}});";
						json.setObj(hasLogin);
					} else {
						json.setSuccess(true);
						json.setMsg("登录成功！");
						user.setIp(ServletActionContext.getRequest().getRemoteAddr());
						ServletActionContext.getRequest().getSession().setAttribute(Constant.USER_SESSION, u);
						List<Pmenu> menus = menuService.getMenuByUser(u); // 加载菜单
						Constant.MENU_USER_KEY_MAP.put(u.getId(), menus);
						messagePush.updateFriendState(true); // 更新用户状态
					}
				}
			} else {
				json.setMsg("用户名或密码错误！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			json.setMsg("登录失败！");
		}
		super.writeToJson(json);
	}

	/**
	 * 强制登录
	 */
	public void doNotNeedSession_mandateLogin() {
		Json json = new Json();
		Puser u = userService.login(user);
		HttpSession usession = Constant.onlineUserSession.get(u.getId());
		if (null != usession) {
			try {
				messagePush.sendMsgToUser(usession, "您已被系統踢出<br>原因：重复登录", "window.location.reload(true);");
				usession.invalidate();
			} catch (Exception e) {
			}
		}
		json.setSuccess(true);
		json.setMsg("登录成功！");
		user.setIp(ServletActionContext.getRequest().getRemoteAddr());
		ServletActionContext.getRequest().getSession().setAttribute(Constant.USER_SESSION, u);
		List<Pmenu> menus = menuService.getMenuByUser(u); // 加载菜单
		Constant.MENU_USER_KEY_MAP.put(u.getId(), menus);
		messagePush.updateFriendState(true); // 更新用户状态

		super.writeToJson(json);
	}

	public void doNotNeedSession_logout() {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		if (null != puser) {
			MessagePush.getUserMessage().remove(puser.getId()); // 用户退出，清楚消息list
		}
		try {
			messagePush.updateFriendState(false); // 更新用户状态
		} catch (Exception e) {
		}

		ServletActionContext.getRequest().getSession().invalidate(); // 清除用户Session

		Json j = new Json();
		j.setSuccess(true);
		super.writeToJson(j);
	}

	public void getLoginUserInfo() {
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		super.writeToJson(puser);
	}

	/**
	 * 更改用户信息
	 */
	public void setUserInfo() {
		Json json = new Json();
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		if (null == user.getDisplayName() || "".equals(user.getDisplayName())) {
			json.setMsg("显示名称不能为空！");
		} else if (null == user.getPuserExtend().getPhone() || "".equals(user.getPuserExtend().getPhone().trim())) {
			json.setMsg("电话号码不能为空！");
		} else {
			puser.setDisplayName(user.getDisplayName());
			puser.getPuserExtend().setAddr(user.getPuserExtend().getAddr());
			puser.getPuserExtend().setEmail(user.getPuserExtend().getEmail());
			puser.getPuserExtend().setPhone(user.getPuserExtend().getPhone());
			try {
				userService.updateUserInfo(puser);
				json.setSuccess(true);
				json.setMsg("修改信息成功！");
			} catch (Exception e) {
				logger.error(e.getMessage());
				e.printStackTrace();
				json.setMsg("修改信息失败！");
			}
		}

		super.writeToJson(json);
	}

	public void changePassword() {
		Json json = new Json();
		Puser puser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);
		String oldPwd = ServletActionContext.getRequest().getParameter("oldPwd");
		try {
			oldPwd = StringUtils.encrypt(oldPwd); // 老密码加密
			if (null != oldPwd && oldPwd.equals(puser.getPwd())) {
				String pwd = StringUtils.encrypt(user.getPwd()); // 密码加密
				puser.setPwd(pwd);
				userService.updateUserInfo(puser);
				json.setSuccess(true);
				json.setMsg("修改密码成功！");
			} else {
				json.setMsg("修改密码失败，原密码不正确！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			json.setMsg("修改密码失败！");
		}
		super.writeToJson(json);
	}

	public void searchUserItemByName() {
		Map<String, Object> valueMap = userService.getUserItemByName(user);

		super.writeToJson(valueMap);
	}

	/**
	 * 验证用户名唯一性
	 */
	public void validateUserName() {
		Json json = new Json();
		try {
			Tuser tuser = userService.getUserByName(user.getName());
			if (null == tuser) {
				json.setSuccess(true);
			} else {
				json.setMsg("用户已存在！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			json.setMsg("获取用户是否存在信息失败！");
		}
		super.writeToJson(json);
	}

	/**
	 * 分页获取数据管理员
	 */
	public void admin_getAllUser() {
		Map<String, Object> usersMap = new HashMap<String, Object>();
		String p = ServletActionContext.getRequest().getParameter("page");
		String r = ServletActionContext.getRequest().getParameter("rows");
		int page = 0;
		int rows = 0;
		try {
			page = Integer.parseInt(p);
			rows = Integer.parseInt(r);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		}
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, String> conditions = new HashMap<String, String>();
			params.put("u.userType", Constant.USERTYPE_USER);
			params.put("srm.type", Constant.SYSROLE_MEMBER_TYPE_USER);
			params.put("sr.roleName", "数据管理员");
			conditions.put("u.userType", "=");
			conditions.put("srm.type", "=");
			conditions.put("sr.roleName", "=");

			BeanInfo linkedBean = Introspector.getBeanInfo(user.getClass());
			PropertyDescriptor lpds[] = linkedBean.getPropertyDescriptors();
			for (int l = 0; l < lpds.length; l++) {
				String linkName = lpds[l].getName();
				Method linkMethod = lpds[l].getReadMethod();
				if ("class".equals(linkName)) {
					continue;
				}
				if ("puserExtend".equals(linkName)) {
					PuserExtend pe = (PuserExtend) linkMethod.invoke(user);

					BeanInfo extendBean = Introspector.getBeanInfo(pe.getClass());
					PropertyDescriptor epds[] = extendBean.getPropertyDescriptors();
					for (int e = 0; e < epds.length; e++) {
						String extName = epds[e].getName();
						Method extMethod = epds[e].getReadMethod();
						if ("class".equals(extName)) {
							continue;
						}
						if (null != extMethod.invoke(pe) && !"".equals(extMethod.invoke(pe))) {
							params.put("ue." + extName, "%" + extMethod.invoke(pe) + "%");
							conditions.put("ue." + extName, "like");
						}
					}
				} else {
					if (null != linkMethod.invoke(user) && !"".equals(linkMethod.invoke(user))) {
						params.put("u." + linkName, "%" + linkMethod.invoke(user) + "%");
						conditions.put("u." + linkName, "like");
					}
				}

			}

			long userNum = userService.getUserNum(params, conditions);
			List<Tuser> tusers = userService.getUserPagination(params, conditions, page, rows);

			List<Puser> user_list = new ArrayList<Puser>();
			if (null != tusers && tusers.size() > 0) {
				for (Tuser tuser : tusers) {
					Puser puser = new Puser();
					BeanUtils.copyProperties(tuser, puser);
					Set<UserExtend> ues = tuser.getUserExtends();
					if (null != ues && ues.size() > 0) {
						BeanUtils.copyProperties(ues.iterator().next(), puser.getPuserExtend());
					}
					user_list.add(puser);
				}
			}
			usersMap.put("total", userNum);
			usersMap.put("rows", user_list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		super.writeToJson(usersMap);
	}

	/**
	 * 分页获取企业用户
	 */
	public void admin_getAllCompanyUser() {
		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		Map<String, Object> usersMap = new HashMap<String, Object>();
		String p = ServletActionContext.getRequest().getParameter("page");
		String r = ServletActionContext.getRequest().getParameter("rows");
		int page = 0;
		int rows = 0;
		try {
			page = Integer.parseInt(p);
			rows = Integer.parseInt(r);
		} catch (NumberFormatException e1) {
			e1.printStackTrace();
		}
		try {
			Map<String, Object> params = new HashMap<String, Object>();
			Map<String, String> conditions = new HashMap<String, String>();
			params.put("u.userType", Constant.USERTYPE_COMPANY);
			params.put("srm.type", Constant.SYSROLE_MEMBER_TYPE_USER);
			params.put("sr.roleName", "企业数据员");
			conditions.put("u.userType", "=");
			conditions.put("srm.type", "=");
			conditions.put("sr.roleName", "=");
			if (!"admin".equals(loginUser.getName()) && sysRoleService.isSysRole(loginUser.getId(), Constant.SYSROLE_MEMBER_TYPE_USER, "数据管理员")) {
				params.put("u.parentid", loginUser.getId());
				conditions.put("u.parentid", "=");
			}

			BeanInfo linkedBean = Introspector.getBeanInfo(user.getClass());
			PropertyDescriptor lpds[] = linkedBean.getPropertyDescriptors();
			for (int l = 0; l < lpds.length; l++) {
				String linkName = lpds[l].getName();
				Method linkMethod = lpds[l].getReadMethod();
				if ("class".equals(linkName)) {
					continue;
				}
				if ("puserExtend".equals(linkName)) {
					PuserExtend pe = (PuserExtend) linkMethod.invoke(user);

					BeanInfo extendBean = Introspector.getBeanInfo(pe.getClass());
					PropertyDescriptor epds[] = extendBean.getPropertyDescriptors();
					for (int e = 0; e < epds.length; e++) {
						String extName = epds[e].getName();
						Method extMethod = epds[e].getReadMethod();
						if ("class".equals(extName)) {
							continue;
						}
						if (null != extMethod.invoke(pe) && !"".equals(extMethod.invoke(pe))) {
							params.put("ue." + extName, "%" + extMethod.invoke(pe) + "%");
							conditions.put("ue." + extName, "like");
						}
					}
				} else {
					if (null != linkMethod.invoke(user) && !"".equals(linkMethod.invoke(user))) {
						params.put("u." + linkName, "%" + linkMethod.invoke(user) + "%");
						conditions.put("u." + linkName, "like");
					}
				}

			}

			long userNum = userService.getUserNum(params, conditions);
			List<Tuser> tusers = userService.getUserPagination(params, conditions, page, rows);

			List<Puser> user_list = new ArrayList<Puser>();
			if (null != tusers && tusers.size() > 0) {
				for (Tuser tuser : tusers) {
					Puser puser = new Puser();
					BeanUtils.copyProperties(tuser, puser);
					Set<UserExtend> ues = tuser.getUserExtends();
					if (null != ues && ues.size() > 0) {
						BeanUtils.copyProperties(ues.iterator().next(), puser.getPuserExtend());
					}
					user_list.add(puser);
				}
			}

			usersMap.put("total", userNum);
			usersMap.put("rows", user_list);
		} catch (Exception e) {
			e.printStackTrace();
		}

		super.writeToJson(usersMap);
	}

	public void getCompanyTree() {
		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		List<TreeNode> tree = userService.getCompanyTree(loginUser);
		
		super.writeToJson(tree);
	}

	/**
	 * 获取用户信息
	 */
	public void admin_getUserInfo() {
		Tuser tuser = userService.getUserById(user.getId());
		Puser puser = new Puser();
		if (null != tuser) {
			BeanUtils.copyProperties(tuser, puser);
			Set<UserExtend> ues = tuser.getUserExtends();
			if (null != ues && ues.size() > 0) {
				BeanUtils.copyProperties(ues.iterator().next(), puser.getPuserExtend());
			}
		}

		super.writeToJson(puser);
	}

	/**
	 * 添加用户
	 */
	public void admin_saveUser() {
		Json json = new Json();
		try {
			if (null == user || null == user.getName() || "".equals(user.getName().trim())) {
				json.setMsg("添加失败，用户名不能为空！");
			} else if (null == user.getDisplayName() || "".equals(user.getDisplayName().trim())) {
				json.setMsg("添加失败，显示名称不能为空！");
			} else if (null == user.getUserType()) {
				json.setMsg("添加失败，用户类型不能为空！");
			} else if (null == user.getPuserExtend().getPhone() || "".equals(user.getPuserExtend().getPhone().trim())) {
				json.setMsg("添加失败，电话号码不能为空！");
			} else {
				user.setPwd("123456");
				userService.save(user);
				json.setSuccess(true);
				json.setMsg("添加成功！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			json.setMsg("添加失败！" + e.getStackTrace());
		}
		super.writeToJson(json);
	}

	/**
	 * 修改用户信息
	 */
	public void admin_setUserInfo() {
		Json json = new Json();
		if (null == user.getDisplayName() || "".equals(user.getDisplayName().trim())) {
			json.setMsg("修改失败，显示名称不能为空！");
		} else if (null == user.getPuserExtend().getPhone() || "".equals(user.getPuserExtend().getPhone().trim())) {
			json.setMsg("修改失败，电话号码不能为空！");
		} else {
			Tuser tuser = userService.getUserById(user.getId());
			Puser puser = new Puser();
			if (null != tuser) {
				BeanUtils.copyProperties(tuser, puser);
				Set<UserExtend> ues = tuser.getUserExtends();
				if (null != ues && ues.size() > 0) {
					BeanUtils.copyProperties(ues.iterator().next(), puser.getPuserExtend());
				}
			}
			puser.setDisplayName(user.getDisplayName());
			puser.getPuserExtend().setAddr(user.getPuserExtend().getAddr());
			puser.getPuserExtend().setEmail(user.getPuserExtend().getEmail());
			puser.getPuserExtend().setPhone(user.getPuserExtend().getPhone());
			try {
				userService.updateUserInfo(puser);
				json.setSuccess(true);
				json.setMsg("修改信息成功！");
			} catch (Exception e) {
				logger.error(e.getMessage());
				e.printStackTrace();
				json.setMsg("修改信息失败！");
			}
		}
		
		super.writeToJson(json);
	}

	/**
	 * 更改用户状态
	 */
	public void admin_changeUserState() {
		Json json = new Json();
		try {

			if (Constant.STATE_CLOSE == user.getUserState() || Constant.STATE_OPEN == user.getUserState()) {
				Tuser tuser = userService.getUserById(user.getId());
				// 更改用户状态
				tuser.setUserState(user.getUserState());

				userService.updateUserInfo(tuser);
				json.setSuccess(true);
				json.setMsg("操作成功！");
			} else {
				json.setMsg("非法操作！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			e.printStackTrace();
			json.setMsg("操作失败！");
		}

		super.writeToJson(json);
	}

}
